package com.ls.lserp.modules.setting.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.setting.entity.CompanyList;
import com.ls.lserp.modules.setting.service.QueryCompanyService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.utils.DictUtils;

import groovy.util.ResourceException;

/**
 * @ClassName: QureyCompanyController
 * @Description:
 * 
 * @author 许天航
 * @date 2017年01月09日
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/mycompany/message/")
public class QueryCompanyController extends BaseController {

	@Autowired
	private QueryCompanyService queryCompanyService;

	/**
	 * 查询公司一览画面
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String queryCom(CompanyList companyList, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		return "modules/setting/queryCompany";

	}

	/**
	 * 拼接一览画面
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("mycompany:message:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(CompanyList companyList, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		FileUtils filUtils = new FileUtils();
		DateFormat dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		// ajax回调时使用的一览list名
		request.setAttribute("listNames", "company");
		// 画面取得的检索项目
		String companyName = companyList.getCompanyName();
		String strUri = request.getContextPath() + Global.getAdminPath();

		// 拼接字符串供分页使用
		String searchParam = "&companyName=" + companyName;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		// 查询一览页面数据
		Page<CompanyList> page = queryCompanyService.findCompanyList(new Page<CompanyList>(request, response),
				companyList);
		// 读取系统路径
		String basePath = SystemPath.getClassPath();
		String tempFilePath = "//" +basePath + "templates//demoHtml//companyList.txt";
		// 读取文件生成字符串
		String companyHtml = readTxtFile(tempFilePath);
		String createUser = "";
		String strHtml = "";
		int pageNo = 0;
		if (!"".equals(companyHtml)) {
			for (int i = 0; i < page.getList().size(); i++) {
				companyHtml = filUtils.readFileToHtml(tempFilePath);
				// 画面No
				pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
				companyHtml = companyHtml.replace("pageNo", "" + pageNo);
				// 分类代码
				companyHtml = companyHtml.replace("companyName",
						StringUtils.checkStringNull(page.getList().get(i).getCompanyName()));
				String companyline = "\"popup('800px','519px','" + strUri + "/mycompany/message/viewCom?companyID="
						+ page.getList().get(i).getCompanyID() + "&editFlag=0')\"";
				// 分类id
				companyHtml = companyHtml.replace("companyId", companyline);
				// 分类公司简称
				companyHtml = companyHtml.replace("companyShortName",
						StringUtils.checkStringNull(page.getList().get(i).getCompanyShortName()));
				
				
//				// 分类公司类型
//				companyHtml = companyHtml.replace("companyType",
//						StringUtils.checkStringNull(page.getList().get(i).getCompanyType()));
//				// 分类公司等级
//				companyHtml = companyHtml.replace("companyRank",
//						StringUtils.checkStringNull(page.getList().get(i).getCompanyRank()));
				
				
				
				// 分类公司地址
				companyHtml = companyHtml.replace("companyAddress",
						StringUtils.checkStringNull(page.getList().get(i).getCompanyAddress()));
				// 分类联系人
				companyHtml = companyHtml.replace("companyCountry", DictUtils.getDictName(StringUtils.checkStringNull(page.getList().get(i).getCompanyCountry())));
				// 分类联系电话
				companyHtml = companyHtml.replace("companyCity", DictUtils.getDictName(StringUtils.checkStringNull(page.getList().get(i).getCompanyCity())));
				// 分类公司邮编
				companyHtml = companyHtml.replace("companyPostCode",
						StringUtils.checkStringNull(page.getList().get(i).getCompanyPostCode()));
				// 描述
				companyHtml = companyHtml.replace("remarks",
						StringUtils.checkStringNull(page.getList().get(i).getCompanyRemark()));
				// 创建人
				createUser = StringUtils.checkStringNull(page.getList().get(i).getCreateBy().getFirstName());
				companyHtml = companyHtml.replace("createUser", createUser);
				// 创建日期
				dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Date createDate = page.getList().get(i).getCreateDate();
				companyHtml = companyHtml.replace("createDate", dateForamat.format(createDate));
				strHtml += companyHtml;
			}
		}
		listMap.put("company", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}

	/**
	 * 创建公司信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("mycompany:message:view")
	@RequestMapping(value = "createCom")
	public String createCom(CompanyList companyList, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		model.addAttribute("companyList", companyList);
		return "modules/setting/createCompany";

	}

	/**
	 * 编辑公司信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("mycompany:message:view")
	@RequestMapping(value = "editCom")
	public String editCom(CompanyList companyList, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String eflag = companyList.getEditFlag();
		List<CompanyList> bankList = queryCompanyService.findBankAccount(companyList);
		companyList = queryCompanyService.findACompany(companyList);
		companyList.setCompanyAccountList(bankList);
		companyList.setEditFlag(eflag);
		model.addAttribute("companyList", companyList);
		return "modules/setting/createCompany";

	}

	/**
	 * 创建保存公司信息
	 * 
	 * @return
	 * @throws ParseException
	 */
	@RequiresPermissions("mycompany:message:edit")
	@ResponseBody
	@RequestMapping(value = "createComSave")
	public String createComSave(CompanyList companyList, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ParseException ,ResourceException{

		
		// 保存成功返回提示信息
		try {
			
			queryCompanyService.insertCompany(companyList);
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "company_edit_save_msg_success")));
			
			
			
		} catch (SQLException sql) {
			
			
			return renderString(response,AjaxDone.error(getText("company_edit_save_msg_fail")));
			
			
		}
		
	}

	/**
	 * 编辑保存公司信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("mycompany:message:edit")
	@RequestMapping(value = "editComSave")
	@ResponseBody
	public String editComSave(CompanyList companyList, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		// 保存成功返回提示信息
		try {
			
			queryCompanyService.updateCompany(companyList);
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "company_edit_save_msg_success")));


			
		} catch (SQLException sql) {
			
			return renderString(response,AjaxDone.error(getText("company_edit_save_msg_fail")));
			
			
		}

	}

	/**
	 * 查看一条公司信息
	 * 
	 * @return
	 */
	@RequiresPermissions("mycompany:message:view")
	@RequestMapping(value = "viewCom")
	public String viewCom(CompanyList companyList, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String flag = companyList.getEditFlag();
		companyList = queryCompanyService.findACompany(companyList);
		List<CompanyList> bankList = queryCompanyService.findBankAccount(companyList);
		companyList.setEditFlag(flag);
		companyList.setCompanyAccountList(bankList);
		model.addAttribute("companyList", companyList);
		return "modules/setting/createCompany";

	}

	/**
	 * 添加银行账户
	 * 
	 * @return
	 */

	@RequestMapping(value = "addBank")
	public String addBank(CompanyList companyList, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		model.addAttribute("companyList", companyList);
		return "modules/setting/addBankAccount";

	}
	
	/**
     * 联动返回城市
     * @param code
     * @param model
     * @return
     */
    @RequestMapping(value = "city")
    @ResponseBody
    public String city(String code,HttpServletResponse response ) {
    	
    	/*前台返回国家code值写入code，调用方法查询code值下的城市列表*/
        List<Dict> cityList=DictUtils.getDictList(code); 
        
        return renderString(response, cityList);
       
    }

}